<!-- 上传头像 -->
<template>
  <el-dialog
    title="修改头像"
    :visible="editAvatarDialog"
    width="60%"
    @close="close()"
  >
    <el-row type="flex" justify="center">
      <div class="cropper">
        <vueCropper
          ref="cropper"
          :img="option.img"
          :outputSize="option.size"
          :outputType="option.outputType"
          :info="option.info"
          :full="option.full"
          :canMove="option.canMove"
          :canMoveBox="option.canMoveBox"
          :original="option.original"
          :autoCrop="option.autoCrop"
          :autoCropWidth="option.autoCropWidth"
          :autoCropHeight="option.autoCropHeight"
          :fixedBox="option.fixedBox"
          @realTime="realTime"
        ></vueCropper>
      </div>
      <div class="previewBox">
        <div :style="previews.div" class="preview">
          <img :src="previews.url" :style="previews.img" />
        </div>
        <el-row type="flex" justify="center">
          <el-upload
            action=""
            :show-file-list="false"
            :auto-upload="false"
            :on-change="uploadImg"
          >
            <el-button size="mini" type="primary"> 更换头像 </el-button>
          </el-upload>
        </el-row>
        <el-row style="margin-top: 15px">
          <el-button
            icon="el-icon-plus"
            circle
            size="mini"
            @click="changeScale(1)"
          ></el-button>
          <el-button
            icon="el-icon-minus"
            circle
            size="mini"
            @click="changeScale(-1)"
          ></el-button>
          <el-button
            icon="el-icon-download"
            circle
            size="mini"
            @click="down('blob')"
          ></el-button>
          <el-button
            icon="el-icon-refresh-left"
            circle
            size="mini"
            @click="rotateLeft"
          ></el-button>
          <el-button
            icon="el-icon-refresh-right"
            circle
            size="mini"
            @click="rotateRight"
          ></el-button>
        </el-row>
      </div>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button @click="close()">取 消</el-button>
      <el-button type="primary" @click="saveEditAvatar">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { VueCropper } from "vue-cropper";
import request from "@/utils/request.js";
import { getFormData, md5_file } from "@/components/ImageCropper/utils/md5Img";
export default {
  components: { VueCropper },
  props: {
    option: Object,
    ruleForm: Object,
    editAvatarDialog: Boolean,
    avatar: String,
  },
  data() {
    return {
      previews: {},
    };
  },
  methods: {
    //关闭弹窗
    close() {
      this.$emit("update:editAvatarDialog", false);
    },
    // 保存头像修改
    saveEditAvatar() {
      this.close();
      this.finish("blob");
    },
    // 放大/缩小
    changeScale(num) {
      num = num || 1;
      this.$refs.cropper.changeScale(num);
    },
    // 左旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft();
    },
    // 右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight();
    },
    // 保存上传图片
    finish(type) {
      if (type === "blob") {
        this.$refs.cropper.getCropBlob(async (data) => {
          // 上传图片
          this.ImgFile = data;
          const endpoint = "https://oss.sunxinao.cn";
          const prefix = "/running-job/upload/";
          md5_file(this.ImgFile)
            .then((result) => {
              this.md5Code = result.toString();
              this.imgUrl = endpoint + prefix + this.md5Code;
              this.do_upload(this.imgUrl, this);
            })
            .catch((error) => {
              this.$message({
                type: "error",
                msg: "上传失败，请重试",
              });
            });
        });
      } else {
        this.$refs.cropper.getCropData((data) => {
          //访问接口保存到数据库写这儿!
        });
      }
    },
    //弹出信息
    openError() {
        this.$message({
          showClose: true,
          message: '修改失败,稍后重试！！！',
          type: 'error'
        });
      },
    //修改用户信息
    async saveChange(ruleForm) {
      let status = await this.$store.dispatch("personCenter/change_User", {
        id: this.ruleForm.id,
        ruleForm,
      });
      if (status == 200 || status == 204) {
        this.$message({
          type: "success",
          message: "修改成功!",
        });
        setTimeout(() => {
          this.$store.commit('user/UPDATE_AVATAR',{avatar:ruleForm.avatar});
          // this.$store.dispatch('personCenter/getUser');
        }, 500);
      } else {
        this.openError();
      }
    },
    async do_upload(url, that) {
      let exist =
        (
          await request.head(url, {
            validateStatus: function () {
              return true; // 把所有响应码视为正常防止抛异常
            },
          })
        )["status"] /
          100 ===
        2;
      if (exist) {
        let user = that.ruleForm;
        user.avatar = that.imgUrl;
        that.saveChange(user);
      } else {
        let token = localStorage.getItem("bearerToken") || "";
        String.prototype.isEmpty = function () {
          return this.length === 0;
        };
        if (token.isEmpty()) {
          await getRefreshToken();
        }
        let form = await getFormData(this.md5Code);
        if (form === undefined) {
          that.openError();
        }
        const endpoint = "https://oss.sunxinao.cn";
        form.append("file", this.ImgFile);
        request({
          url: endpoint,
          method: "POST",
          data: form,
          onUploadProgress: function (e) {
            if (e.lengthComputable) {
              that.progress = (e.loaded / e.total) * 100;
            }
          },
        })
          .then(function (data) {
            let user = that.ruleForm;
            user.avatar = that.imgUrl;
            that.saveChange(user);
          })
          .catch(function (error) {
            that.openError();
          });
      }
    },
    // 实时预览函数
    realTime(data) {
      this.previews = data;
    },
    // 下载图片
    down(type) {
      var aLink = document.createElement("a");
      aLink.download = "author-img";
      if (type === "blob") {
        this.$refs.cropper.getCropBlob((data) => {
          aLink.href = window.URL.createObjectURL(data);
          aLink.click();
        });
      } else {
        this.$refs.cropper.getCropData((data) => {
          aLink.href = data;
          aLink.click();
        });
      }
    },
    // 更换头像--上传本地图片
    uploadImg(file) {
      var _this = this;
      var reader = new FileReader();
      reader.onload = (e) => {
        let data;
        if (typeof e.target.result === "object") {
          // 把Array Buffer转化为blob 如果是base64不需要
          data = window.URL.createObjectURL(new Blob([e.target.result]));
        } else {
          data = e.target.result;
        }
        _this.option.img = data;
      };
      // 转化为base64
      reader.readAsDataURL(file.raw);
      // 转化为blob
      // reader.readAsArrayBuffer(file.raw);
    },
  },
};
</script>
<style lang="scss" scoped>
.previewBox {
  text-align: center;
  margin-left: 60px;
}

.preview {
  width: 150px;
  height: 150px;
  margin: 0px auto 20px auto;
  border-radius: 50%;
  border: 1px solid #ccc;
  background-color: #ccc;
  overflow: hidden;
}

.cropper {
  width: 260px;
  height: 260px;
}
</style>
